<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.searchKey"
        placeholder="请输入关键词"
        style="width: 200px;margin-right: 20px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
    <!-- <el-input v-model="Pages.readName" placeholder="开始时间"> </el-input> -->
        <el-date-picker
                v-model="listQuery.startTime"
                type="datetime"
                placeholder="开始时间">
        </el-date-picker>

        <el-date-picker
            v-model="listQuery.endTime"
            type="datetime"
            placeholder="结束时间">
        </el-date-picker>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-refresh"
        @click="handleFilter"
      >
        刷新
      </el-button>
      <el-button
        v-has="'videoList:add'"
        v-waves
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        {{ $t('table.add') }}
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
    <!-- 前面的勾选按钮 -->
     <el-table-column
      type="selection"
      width="55"
      header-align="center"
      align="center"
      >
    </el-table-column>

    <el-table-column
      prop="id"
      label="id序号"
      width="85"
      align="center"
      header-align="center"
     >
    </el-table-column>

	<!-- 排除ID主键 -->
      <el-table-column :label="tempDesc.firstImg" width="200px" show-overflow-tooltip>
        <template slot-scope="scope">
          <div class="demo-image">
            <img width="100px" height="90px" :src="scope.row.firstImg" alt="" />
          </div>
        </template>
      </el-table-column>

      <el-table-column v-if="checkBtnPermission(['videoList:edit',])"  :label="tempDesc.username" width="100px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>



      <el-table-column :label="tempDesc.videoName" width="260px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.videoName }}</span>
        </template>
      </el-table-column>
      
      <el-table-column   label="视频大小" width="100px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.videoSize }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="播放" width="150px" show-overflow-tooltip>
         <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="playVideo(scope.row)">
              播放
            </el-button>

        </template>
      </el-table-column>

      <el-table-column label="复制代码" width="300px" show-overflow-tooltip>
        <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="lookCode(scope.row)">
              查看代码
            </el-button>
            <el-button type="primary" size="mini" @click="copyCode(scope.row)">
              复制代码
            </el-button>
        </template>
      </el-table-column>


      <el-table-column label="上传时间" width="180px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>



      <!-- 这里是操作按钮，和权限相关 -->
      <el-table-column v-if="checkBtnPermission(['accountList:edit','videoList:delete','accountList:generateQR'])" :label="$t('table.actions')" align="center" width="310" class-name="small-padding fixed-width">
        <template slot-scope="scope">
        <!--  <el-button v-has="'accountList:edit'" type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)">
            {{ $t('table.edit') }}
          </el-button> -->
          <el-button v-has="'videoList:delete'" type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">
            {{ $t('table.delete') }}
          </el-button>
          <!--
          <el-button v-has="'accountList:generateQR'" type="primary" size="mini" style="width: 130px;margin-left: 10px" icon="el-icon-printer" @click="generateQRUrl(scope.row)">
            生成二维码图片
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 編輯窗口 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="120px"
        style="width: 600px; margin-left:50px;"
      >

      <el-form-item :label="tempDesc.username" prop="username">
        <el-upload
          class="upload-demo"
          drag
          accept=".mp4, .flv, .wav"
          :action="baseurl + '/api/oprvideo/upload'"
          :headers="headers"
          :on-success="uploadSuccess"
          :multiple="false"
          >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只允许上传.mp4, .flv, .wav文件类型，且不能超过 200MB</div>
        </el-upload>
      </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
       <!-- <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button> -->
      </div>
    </el-dialog>


    <!-- 视频播放弹框 -->
    <el-dialog class="video-class" :visible.sync="dialogVisibleShowPlay" :before-close="closePlay">
      <div class="my-center">
        <video :src="videoPlay" width="420" height="440" controls :poster="poster" />
      </div>
    </el-dialog>


    <el-dialog class="video-code" :visible.sync="dialogVisibleShowCode" :before-close="closeCode">
      <div class="my-center">

         <el-input type="textarea" :rows="26"
              :maxlength="1500" v-model="deepCode"
              disabled
              ></el-input>
         <!-- <el-divider></el-divider> -->
         <el-button @click="closeCode">
           关闭
         </el-button>
         <el-button @click="copyCode(myrow)" type="primary">
           复制代码
         </el-button>

      </div>
    </el-dialog>

  </div>
</template>

<script>
import { checkBtnPermission } from '@/utils/permission' // 权限判断函数
import { fetchList, createRow, updateRow, deleteRow, generateQRUrl } from '@/api/xxdvideo/xxdvideo'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import dateToString from '@/utils/DateTimeToString'
import config from '@/config'
import { getToken } from '@/utils/auth'
import templatejs from '@/views/xxdvideo/videoList/template'
// 常量title
const tempDesc = {
  	'id': '主键ID',
  	'username': '上传者',
  	'path': '存储路径',
  	'flag': '1正常 0撤销',
  	'videoName': '视频源名称',
  	'videoNewname': '视频新名称',
  	'updateTime': '更新时间',
  	'createTime': '创建时间',
    'firstImg':'封面图',

}
export default {
  name: 'videoList',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      videoPlay:'',//用于播放视频，关闭后需要清空
      poster:'',
      dialogVisibleShowPlay: false,

      //code
      dialogVisibleShowCode:false,
      deepCode:'',
      myrow:null,

      headers: { 'X-Token': getToken() },
      baseurl: config.context,
      templatejs: templatejs,

      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        searchKey: '',
        startTime: '',
        endTime: '',
      },
      showReviewer: false,
      temp: {
  	     'id': '',
  	     'username': '',
  	     'path': '',
  	     'flag': '',
  	     'videoName': '',
  	     'videoNewname': '',
  	     'updateTime': '',
  	     'createTime': '',

      },
      tempDesc: tempDesc,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '视频上传'
      },
      rules: {
         // username: [{ required: true, message: '请输入' + tempDesc.username, trigger: 'blur' }],
         // path: [{ required: true, message: '请输入' + tempDesc.path, trigger: 'blur' }],
         // flag: [{ required: true, message: '请输入' + tempDesc.flag, trigger: 'blur' }],
         // videoName: [{ required: true, message: '请输入' + tempDesc.videoName, trigger: 'blur' }],
         // videoNewname: [{ required: true, message: '请输入' + tempDesc.videoNewname, trigger: 'blur' }],
        //name: [{ required: true, message: '请输入' + tempDesc.name, trigger: 'blur' }],
        //account: [{ required: true, message: '请输入' + tempDesc.account, trigger: 'blur' }],
        //appid: [{ required: true, message: '请输入' + tempDesc.appid, trigger: 'blur' }],
        //appsecret: [{ required: true, message: '请输入' + tempDesc.appsecret, trigger: 'blur' }],
        //url: [{ required: true, message: '请输入' + tempDesc.url, trigger: 'blur' }],
        //token: [{ required: true, message: '请输入' + tempDesc.token, trigger: 'blur' }],
        //aeskey: [{ required: true, message: '请输入' + tempDesc.aeskey, trigger: 'blur' }]
      }
    }
  },

  created() {
    this.getList()
  },
  methods: {
    checkBtnPermission,
    getList() {
      this.listLoading = true
      //判断时间是否为空
      this.listQuery.startTime = dateToString(this.listQuery.startTime);
      this.listQuery.endTime = dateToString(this.listQuery.endTime);
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.3 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    uploadSuccess(res, file, fileList) {
      // console.log('上传文件成功response : ' + JSON.stringify(res))
      // console.log('上传文件成功file : ' + JSON.stringify(file))
      // console.log('上传文件成功fileList : ' + JSON.stringify(fileList))
      if (res.code != 200) {
        this.$message.error(res.message)
        return false
      }else{
        this.$message({
          message: '上传成功',
          type: 'success'
        });
        this.getList()
      }
      //上传成功，主动关闭弹框
      this.dialogFormVisible=false
    },
    playVideo(row){
      console.log("row：" ,JSON.stringify(row))
      this.videoPlay = row.path;
      this.poster = row.firstImg
      this.dialogVisibleShowPlay=true;

    },
    closePlay(){
       this.dialogVisibleShowPlay=false;
       this.videoPlay = "";
       this.poster ="";
    },

    lookCode(row){
      this.dialogVisibleShowCode = true;
      const domain = "https://video.i0898.org"
      let _templateCode = Object.assign(this.templatejs) ;
      let new_domain = _templateCode.replaceAll('#{domain}','https://video.i0898.org')
      if(row.firstImg != null){
         new_domain = new_domain.replaceAll('#{uploadVideoPoster}',row.firstImg)
      }else{
        new_domain = new_domain.replaceAll('#{uploadVideoPoster}','')
      }
       new_domain = new_domain.replaceAll('#{uploadVideo}',row.path) //mp4存储路径
       new_domain = new_domain.replaceAll('#{videoOldName}',row.videoName) //mp4存储路径
      this.deepCode =new_domain
      this.myrow=row;
    },
    closeCode(){
      this.dialogVisibleShowCode = false;
      this.deepCode = "";
      this.myrow=null;
    },
    copyCode(row){
      let _templateCode = this.templatejs ;
      console.log(_templateCode)
      let new_domain = _templateCode.replaceAll('#{domain}','https://video.i0898.org')
      if(row.firstImg != null){
         new_domain = new_domain.replaceAll('#{uploadVideoPoster}',row.firstImg)
      }
       new_domain = new_domain.replaceAll('#{uploadVideo}',row.path) //mp4存储路径
       new_domain = new_domain.replaceAll('#{videoOldName}',row.videoName) //mp4存储路径
       //this.deepCode =Object.assign(new_domain)



      	var copyInput = document.createElement('input');//创建input元素
      	document.body.appendChild(copyInput);//向页面底部追加输入框
      	copyInput.setAttribute('value', new_domain);//添加属性，将url赋值给input元素的value属性
      	copyInput.select();//选择input元素
      	document.execCommand("Copy");//执行复制命令
      	this.$message.success("代码已复制！");//弹出提示信息，不同组件可能存在写法不同
      	//复制之后再删除元素，否则无法成功赋值
      	copyInput.remove();//删除动态创建的节点

    },
    resetTemp() {
      this.temp = {
  	     'id': '',
  	     'username': '',
  	     'path': '',
  	     'flag': '',
  	     'videoName': '',
  	     'videoNewname': '',
  	     'updateTime': '',
  	     'createTime': '',
        //'id': '',
        //'name': '',
        //'account': '',
        //'appid': '',
        //'appsecret': '',
        //'url': '',
        //'baseAPI': '',
        //'token': '',
        //'aeskey': ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick( () => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createRow(this.temp).then( () => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateRow(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          var params = { 'id': row.id }
          deleteRow(params).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        })
    },
    generateQRUrl(row) {
      this.$confirm('确定生成二维码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const tempData = Object.assign({}, row)
        generateQRUrl(tempData).then(() => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '生成二维码成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    //提示关闭编辑窗口
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
           this.$refs.upload.clearFiles()
        })
        .catch(_ => {});
    }
  }

}
</script>
<style scoped>
  .video-class{
    height: 80%;
    width: 80%;
  }
  .my-center{
    text-align: center;
  }
  .video-code{
    height: 1000px;
    width: 100%;
  }
  /deep/ .el-textarea.is-disabled .el-textarea__inner{
    color: #1e1e1e !important;
  }
</style>
